package com.mybatis.Filter;

import com.alibaba.fastjson.JSONObject;
import com.mybatis.entity.User;
import com.mybatis.mapper.UserMapper;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

/**
 * @Date 2019/11/14
 **/
public class LoginFilter implements Filter {

    private UserMapper userMapper;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(filterConfig.getServletContext());
        userMapper = (UserMapper)context.getBean("userMapper");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //检查用户是否存在
        Integer userId=Integer.valueOf(servletRequest.getParameter("userId"));
        if(null==userId){
            returnResponse(servletResponse);
            return;
        }
        User user=userMapper.selectUserInfo(userId);
        if(null==user){
            System.out.println("用户不存在");
            returnResponse(servletResponse);
            return;
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }



    @Override
    public void destroy() {

    }

    //返回json数据
    protected void returnResponse(ServletResponse response) {
        OutputStream outputStream = null;
        PrintWriter printWriter = null;
        try {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            outputStream = response.getOutputStream();
            printWriter = new PrintWriter(outputStream);

            JSONObject jsonObject=new JSONObject();
            jsonObject.put("code","201");
            jsonObject.put("msg","用户不存在、请登录");
            printWriter.write(jsonObject.toString());
            printWriter.flush();
        } catch (IOException e) {
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                }
            }
            if (printWriter != null) {
                printWriter.close();
            }
        }
    }
}
